import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import { clearSessionStorage, getToken } from '@/util/util'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({showSpinner: false})

export const appBaseUrl = process.env.VUE_APP_ENV === 'local' ? 'api/' : process.env.VUE_APP_BASE_URL

const http = axios.create({
  timeout: 20000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
})

http.interceptors.request.use(
  config => {
    NProgress.start()
    const _config = config
    _config.url = appBaseUrl + _config.url
    return _config
  },
  error => {
    return Promise.reject(error)
  }
)

http.interceptors.response.use(
  response => {
    NProgress.done()
    if (response.data.code === 0) {
      return response.data.data !== null ? response.data.data : true
    }else {
      Message.error(response.data.msg)
    }
  },
  error => {
    NProgress.done()
    return Promise.reject(error)
  }
)

http.get = (url) => {
  let _url = ''
  if(url.indexOf('?') !== -1){
    _url = `${url}&token=${getToken()}`
  }else{
    _url = `${url}?token=${getToken()}`
  }
  return http({
    method: 'get',
    url: _url
  })
}

http.post = (url, data) => {
  let content = ''
  let type = true
  if (url.indexOf('login') === -1) {
    content = `${ data }&token=${ getToken() }`
  } else {
    content = data
  }
  if (url.indexOf('jar/add') > -1) {
    data.token = getToken()
    type = false
  }
  return http({
    method: 'post',
    url,
    data: type ? content : data
  })
}

export default http
